package com.tanguy.driver.utlis.delegation

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import cn.sinata.xldutils_kotlin.xldUtils
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * Created by dab on 2017/10/25 0025 09:12
 * SharedPreferences的委托类
 * 修改这个值,都会修改SharedPreferences内的值
 */

open class SP<T>(var key: String, var defaultValue: T) : ReadWriteProperty<Any?, T> {
    val sp by lazy {
        val name = if (TextUtils.isEmpty(xldUtils.SP_NAME)) {
            xldUtils.context?.packageName + ".sp"
        } else {
            xldUtils.SP_NAME!!
        }
        xldUtils.context!!.getSharedPreferences(name, Context.MODE_PRIVATE)
    }


    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return get(key, defaultValue)

    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        put(key, value)
    }


    @SuppressLint("CommitPrefEdits")
    private fun put(key: String, value: T) = with(sp.edit()) {
        when (value) {
            is Int -> putInt(key, value)
            is String -> putString(key, value)
            is Boolean -> putBoolean(key, value)
            is Long -> putLong(key, value)
            is Float -> putFloat(key, value)
            else -> throw IllegalAccessException("未识别的数据类型")
        }.apply()
    }

    @Suppress("UNCHECKED_CAST")
    private fun get(key: String, defaultValue: T): T = with(sp) {
        when (defaultValue) {
            is Int -> getInt(key, defaultValue) as T
            is String -> getString(key, defaultValue) as T
            is Boolean -> getBoolean(key, defaultValue) as T
            is Long -> getLong(key, defaultValue) as T
            is Float -> getFloat(key, defaultValue) as T
            else -> throw IllegalAccessException("未识别的数据类型")
        }
    }
}

